#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from util import mysql_util

def storage_mysql(gzbd_data):
    connection, cursor = None, None;
    try:
        # 执行插入操作，并提交事务
        connection, cursor = mysql_util.get_connection_cursor()
        for gzbd in gzbd_data:
            date = gzbd["时间"]
            query_sql = "select * from coronavirus where date = '%s'"%(date,)
            insert_sql = "insert into coronavirus(date, region, diagnosis, overseas_import, cure, " \
                         "death, therapy, observation) values ('%s', '%s', %s, %s, %s, %s, %s, %s)"\
                         %(gzbd["时间"], gzbd["地区"], gzbd.get("确诊数", None), gzbd.get("输入数", None),
                           gzbd.get("治愈数", None), gzbd.get("死亡数", None), gzbd.get("隔离数", None),
                           gzbd.get("观察数", None))
            insert_sql = insert_sql.replace("None", "null")

            result = mysql_util.execute_query(query_sql, cursor)
            if len(result):
                continue
            mysql_util.execute_insert_update_delete(insert_sql, cursor)

        mysql_util.commit_(connection)
    except Exception as e:
        print(e)
        # 回滚数据
        mysql_util.rollback_(connection)
    finally:
        # 关闭连接、游标
        mysql_util.close_(connection, cursor)